'use strict';
const { Service } = require('egg');

class BlogService extends Service {

  /**
     * 创建文章
     * @param {*} payload
     */
  async create(payload) {
    const { ctx } = this;
    return ctx.model.Markdown.create(payload);
  }

  /**
   * 查看blog列表
   * @param {*} payload
   */
  async index(payload) {
    const { currentPage, pageSize, isPaging, search } = payload;
    let res = [];
    let count = 0;
    const skip = ((Number(currentPage)) - 1) * Number(pageSize || 10);
    if (isPaging) {
      if (search) {
        res = await this.ctx.model.Markdown.find({ name: { $regex: search } }).populate('author').skip(skip)
          .limit(Number(pageSize))
          .sort({ createdAt: -1 })
          .exec();
        count = res.length;
      } else {
        res = await this.ctx.model.Markdown.find({}).populate('author').skip(skip)
          .limit(Number(pageSize))
          .sort({ createdAt: -1 })
          .exec();
        count = await this.ctx.model.Markdown.count({}).exec();
      }
    } else {
      if (search) {
        res = await this.ctx.model.Markdown.find({ name: { $regex: search } }).populate('author').sort({ createdAt: -1 })
          .exec();
        count = res.length;
      } else {
        res = await this.ctx.model.Markdown.find({}).populate('author').sort({ createdAt: -1 })
          .exec();
        count = await this.ctx.model.Markdown.count({}).exec();
      }
    }
    // 整理数据源 -> Ant Design Pro
    const data = res.map((e, i) => {
      const jsonObject = Object.assign({}, e._doc);
      jsonObject.key = i;
      // jsonObject.password = 'Are you ok?';
      jsonObject.createdAt = this.ctx.helper.formatTime(e.createdAt);
      return jsonObject;
    });

    return { count, list: data, pageSize: Number(pageSize), currentPage: Number(currentPage) };
  }
}


module.exports = BlogService;
